package com.pm.controller.file;

import com.github.pagehelper.PageInfo;
import com.pm.common.Pages;
import com.pm.common.Response;
import com.pm.common.annotation.CurrentUser;
import com.pm.common.annotation.MyLog;
import com.pm.common.annotation.PassToken;
import com.pm.common.annotation.UserLoginToken;
import com.pm.common.exception.ExpCodeState;
import com.pm.entity.Config;
import com.pm.entity.po.file.FileLib;
import com.pm.entity.po.security.User;
import com.pm.service.file.FileService;
import com.pm.utils.DateUtil;
import com.pm.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

@Api(tags = "附件上传库")
@UserLoginToken
@RestController
@RequestMapping("/fileController")
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private Config config;


    @ApiOperation("上传")
    @PassToken
    @RequestMapping("/uploadFile")
    @ResponseBody
    // MultipartFile[]
    public Response<String> uploadFile(@RequestParam MultipartFile file) {
        //MultipartConfigFactory factory = new MultipartConfigFactory();
        String fileName = file.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + config.getPicPath();
        /*String fileName = file.getOriginalFilename();
        //系统目录
        String filePath = System.getProperty("user.dir") + config.getPicPath();
        //File dest = new File(filePath + "/" +  fileName);
        //File dest = new File(new File(filePath).getAbsolutePath() + "/" + fileName);
        File dest = new File(filePath + "/" +  fileName);
        File pfile = new File(filePath);
        System.out.println("filePath+++++++++++++++++++++++++++++++++++" + filePath);
        System.out.println("user.dir+++++++++++++" + System.getProperty("user.dir"));
        System.out.println("pfile+++++++++++++" + pfile);
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        //factory.setLocation(filePath);
        if (dest.exists()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddmmss");
            fileName = sdf.format(Calendar.getInstance().getTime()) + fileName;
            dest = new File(new File(filePath).getAbsolutePath() + "/" + fileName);
        }
        try {
            System.out.println("dest=========" + dest);
            System.out.println("file=========" + file);
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        try {
            return UploadUtil.uploadFile(file, filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return new Response<>(ExpCodeState.upload_error, fileName);
        }
    }

    /**
     * 下载
     * @param filename
     * @param response
     */
    @ApiOperation("下载")
    @PassToken
    @RequestMapping("/{filename:.+}")
    @ResponseBody
    public void outPic(@PathVariable String filename, HttpServletResponse response) {
        java.io.File dest = new java.io.File(System.getProperty("user.dir") + config.getPicPath() + filename);
        try {
            try {
                //获取输出流
                OutputStream stream = response.getOutputStream();
                try {
                    //清空下载文件的空白行（空白行是因为有的前端代码编译后产生的）
                    response.reset();
                    String fileName = "从数据库字段中获取到文件名字";
                    //设置响应头，把文件名字设置好
                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    //解决编码问题
                    response.setContentType("application/octet-stream; charset=utf-8");
                    //创建存储的文件对象（文件存储的路径和文件名字）
                    //输出流开始写出文件（FileUtils是Apache下的工具类可以直接调用）
                    stream.write(FileUtils.readFileToByteArray(dest));
                    //刷新流
                    stream.flush();
                } finally {
                    //关闭流
                    stream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加
     */
    @ApiOperation("新增接口")
    @PostMapping("/addFile")
    @ResponseBody
    @MyLog(value = "文件库添加")
    public Response<Integer> add(@RequestBody FileLib fileLib, @CurrentUser User user) {
        Response<Integer> response = null;
        fileLib.setUserId(user.getUserId());
        Integer result = fileService.add(fileLib);
        if (result > 0) {
            response = new Response<>(ExpCodeState.add_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.add_data_failed);
        }
        return response;
    }

    @ApiOperation("分页查询文件")
    @PostMapping("/getListByPage/{pageNum}/{pageSize}")
    @ResponseBody
    public Response<PageInfo<FileLib>> getList(@RequestBody FileLib fileLib, Pages page) {
        PageInfo<FileLib> result = fileService.getListByPage(fileLib, page);
        Response<PageInfo<FileLib>> res = new Response<PageInfo<FileLib>>(ExpCodeState.query_data_success, result);
        return res;
    }

    @ApiOperation("查询文件")
    @PostMapping("/getList")
    @ResponseBody
    public Response<List<FileLib>> getList(FileLib fileLib) {
        List<FileLib> result = fileService.getList(fileLib);
        Response<List<FileLib>> res = new Response<List<FileLib>>(ExpCodeState.query_data_success, result);
        return res;
    }


    @ApiOperation("删除附件")
    @PostMapping("/deleteFileLib")
    @ResponseBody
    @MyLog(value = "删除附件")
    public Response<Integer> deleteFileLib(@RequestParam("id") Integer id) {
        boolean res = fileService.deleteFileLib(id);
        if (res) {
            return new Response<>(ExpCodeState.remove_data_success);
        } else {
            return new Response<>(ExpCodeState.remove_data_failed);
        }
    }


    /**
     * 添加
     */
    @ApiOperation("新增接口")
    @PostMapping("/addDaily")
    @ResponseBody
    @MyLog(value = "日常文件库添加")
    public Response<Integer> addDaily(@RequestBody FileLib fileLib, @CurrentUser User user) {
        Response<Integer> response = null;
        fileLib.setFileAddTime(new Date());
        fileLib.setFileQuarter(DateUtil.getQuarter(new Date()));
        fileLib.setUserId(user.getUserId());
        Integer result = fileService.add(fileLib);
        if (result > 0) {
            response = new Response<>(ExpCodeState.add_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.add_data_failed);
        }
        return response;
    }


    @ApiOperation("查询日常文件")
    @PostMapping("/getListDaily")
    @ResponseBody
    public Response<List<FileLib>> getListDaily(@RequestBody FileLib fileLib) {
        List<FileLib> result = fileService.getList(fileLib);
        Response<List<FileLib>> res = new Response<List<FileLib>>(ExpCodeState.query_data_success, result);
        return res;
    }


}
